<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>异步处理示例</title>
</head>
<body>
<button id="startButton">开始任务</button>
<div id="message"></div>

<script>
    let socket;
    const startButton = document.getElementById('startButton');
    const messageDiv = document.getElementById('message');

    startButton.addEventListener('click', () => {
        // 建立 WebSocket 连接
        socket = new WebSocket('ws://192.168.94.36:8099/ws?id=1');
        let socketid = '';
        socket.onopen = () => {
            // 发送一个消息给后端，让后端返回 sessionId
            // socket.send('getSessionId');
            // console.log("aa")
            console.log("连接建立成功。。。")
        };

        socket.onmessage = (event) => {
            if (event.data.startsWith('sockId:')) {
                const sockId = event.data.split(':')[1];
                socketid = sockId ;
                const contendId = "100101"
                // 发送请求开始异步任务
                fetch(`http://192.168.94.36:8099/survey/01/startTask/${sockId}/${contendId}`)
                    .then(response => response.text())
                    .then(data => {
                        messageDiv.textContent = data;
                        //alert("后台完成！！！！")
                        console.log(111)
                    });
            } else {
                messageDiv.textContent = event.data;
                console.log(222)
                alert("后台完成。。。！！！")
                socket.close();
                fetch(`http://192.168.94.36:8099/survey/01/removeSessionData/${socketid}`, {
                    method: 'GET'
                })
                    .then(response => {
                        if (response.ok) {
                            return response.text();
                        }
                        throw new Error('请求失败');
                    })
                    .then(data => {
                        console.log('后端响应:', data);
                    })
                    .catch(error => {
                        console.error('请求出错:', error);
                    });
                // socket.onclose = () => {
                //     console.log('WebSocket 连接已关闭');
                //
                //     fetch(`http://localhost:8099/survey/01/removeSessionData/${socketid}`, {
                //         method: 'GET'
                //     })
                //         .then(response => {
                //             if (response.ok) {
                //                 return response.text();
                //             }
                //             throw new Error('请求失败');
                //         })
                //         .then(data => {
                //             console.log('后端响应:', data);
                //         })
                //         .catch(error => {
                //             console.error('请求出错:', error);
                //         });
                // };
            }
        };


    });
</script>
</body>
</html>